package weaver.jobs.zhlx.duss.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.axis.encoding.Base64;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2023年08月22日 11:45
 */
public class ZhlxJobUtil {

    private static final JSONObject propVal = PropUtil.getPropVal("zhlxsap");
    private static final String URL = propVal.getString("url")+"/RESTAdapter/ec/interface";
    private static final String USERNAME = propVal.getString("username");
    private static final String PASSWORD = propVal.getString("password");

    /**
     * 请求处理器
     *
     * @param type
     * @param dataJson
     * @return
     */
    public JSONObject handleOKHttpRequest(String type, JSONObject dataJson) {
        JSONObject paramsJson = new JSONObject();
        JSONObject inuptJson = new JSONObject();
        String fullDate = DateUtil.getFullDate();
        String curdate = fullDate.substring(0, 10).replace("-", "");
        String curtime = fullDate.substring(11, 19).replace(":", "");
        JSONObject headerJson = new JSONObject();
        headerJson.put("SYSID", "EC");
        headerJson.put("BUSINESS", type);
        headerJson.put("BUSNKEY", "");
        headerJson.put("TECHKEY", getUUIDStr());
        headerJson.put("DATE", curdate);
        headerJson.put("TIME", curtime);
        inuptJson.put("HEADER", headerJson);
        inuptJson.put("DATA", dataJson);
        paramsJson.put("INPUT", inuptJson.toJSONString());
        return sendOKHttpRequest(paramsJson);
    }

    /**
     * 发送HTTP请求
     *
     * @param params
     * @return
     */
    public JSONObject sendOKHttpRequest(JSONObject params) {
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String message = "";
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());
            Request request = new Request.Builder()
                    .url(URL)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                resultJson = JSONObject.parseObject(result);
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 建模权限重构
     *
     * @param userid
     * @param formmodeid
     * @param id
     */
    public void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     *
     * @param modeid
     * @param paramJson
     * @return
     */
    public int insertModelData(int modeid, JSONObject paramJson) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        String sql = "select b.tablename,a.formid from modeinfo a left join workflow_bill b on a.formid=b.id where a.id=?";
        rs.executeQuery(sql, modeid);
        rs.next();
        String tablename = Util.null2String(rs.getString("tablename"));
        String uuid = UUID.randomUUID().toString();
        String insSql = "insert into " + tablename
                + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
        Object[] params = {uuid, 1, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
        if (rs.executeUpdate(insSql, params)) {
            rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
            rs1.next();
            dataid = Util.getIntValue(rs1.getString("id"));
            if (dataid > 0) {
                Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
                //遍历数据 进行update
                String updatesql = "update " + tablename + " set ";
                Set<String> keySet = map.keySet();
                for (String key : keySet) {
                    updatesql += key + "='" + map.get(key) + "',";
                }
                if (updatesql.endsWith(",")) {
                    updatesql = updatesql.substring(0, updatesql.length() - 1);
                    updatesql += " where id=" + dataid;
                    rs.executeUpdate(updatesql);
                }
                //进行权限重构
                newModeRight(1, modeid, dataid);
            }
        }
        return dataid;
    }

    /**
     * 更新明细数据
     *
     * @param tablename
     * @param paramJson
     * @return
     */
    public boolean insertDetailData(String tablename, JSONObject paramJson) {
        BaseBean baseBean = new BaseBean();
        String insertsql = "insert into " + tablename + "";
        String keyString = "";
        String valueString = "";
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            keyString += key + ",";
            valueString += "'" + map.get(key) + "',";
        }
        if (keyString.endsWith(",")) {
            keyString = keyString.substring(0, keyString.length() - 1);
        }
        if (valueString.endsWith(",")) {
            valueString = valueString.substring(0, valueString.length() - 1);
        }
        insertsql += "(" + keyString + ") values(" + valueString + ")";
        baseBean.writeLog(">>>>>insertDetailData>>>>insertsql=" + insertsql);
        RecordSet rs = new RecordSet();
        return rs.executeUpdate(insertsql);
    }

    /**
     * 更新数据
     *
     * @param tablename 表名
     * @param paramJson 数据集合
     * @param dataid    更新用唯一标识
     * @return
     */
    public boolean updateModelData(String tablename, int dataid, JSONObject paramJson) {
        RecordSet rs = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String updatesql = "update " + tablename + " set  ";
        String valuesStr = "";
        Map<String, Object> map = JSONObject.toJavaObject(paramJson, Map.class);
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            if (valuesStr.equals("")) {
                valuesStr = key + "='" + map.get(key) + "'";
            } else {
                valuesStr += "," + key + "='" + map.get(key) + "'";
            }
        }
        updatesql += valuesStr + " where id='" + dataid + "'";
        baseBean.writeLog(">>>>>updateModelData>>>>updatesql=" + updatesql);
        return rs.execute(updatesql);
    }

    /**
     * 删除数据
     *
     * @param tablename 表名
     * @param dataid    更新用唯一标识
     * @return
     */
    public boolean deleteDetailData(String tablename, int dataid) {
        RecordSet rs = new RecordSet();
        BaseBean baseBean = new BaseBean();
        String deletesql = "delete " + tablename + " where mainid='" + dataid + "'";
        baseBean.writeLog(">>>>>deleteDetailData>>>>deletesql=" + deletesql);
        return rs.executeUpdate(deletesql);
    }

    /**
     * 获取uuid
     *
     * @return
     */
    public String getUUIDStr() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }

    /**
     * 获取建模Id
     *
     * @param tablename
     * @return
     */
    public int getFormmodeid(String tablename) {
        RecordSet rs = new RecordSet();
        String sql = "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?";
        rs.executeQuery(sql, tablename);
        rs.next();
        return Util.getIntValue(rs.getString("id"));
    }

    /**
     * 获取是否存在重复数据
     *
     * @param tablename
     * @param fieldname
     * @param fieldvalue
     * @return
     */
    public int getMainId(String tablename, String fieldname, String fieldvalue) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from " + tablename + " where " + fieldname + "=?", fieldvalue);
        rs.next();
        return Util.getIntValue(rs.getString(1), -1);
    }

    /**
     * 获取银行信息
     *
     * @param yxdm
     * @return
     */
    public String getKhyh(String yxdm) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select yxmc from uf_sd_bk_jm where yxdm=?", yxdm);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
}
